package net.lc7.curator;

import net.lc7.util.ZkPropertiesUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.retry.RetryNTimes;

/**
 * @Description:  Curator实现监听功能
 *
 * Path Cache：监视一个路径下1）孩子结点的创建、2）删除，3）以及结点数据的更新。产生的事件会传递给注册的PathChildrenCacheListener。
 * Node Cache：监视一个结点的创建、更新、删除，并将结点的数据缓存在本地。
 * Tree Cache：Path Cache和Node Cache的“合体”，监视路径下的创建、更新、删除事件，并缓存路径下所有孩子结点的数据。
 *
 * @Author: Jason.zhu
 * @Create: 2019/05/27 11:10
 */

public class CuratorWatchClient {

    private static String watcherNode = "/watcherNode";

    public static void main(String[] args) throws Exception {
        CuratorFramework curatorFrameworkClient = CuratorFrameworkFactory.newClient(
                                                        ZkPropertiesUtil.getZkServerIp(),
                                                        new RetryNTimes(10, 5000));
        curatorFrameworkClient.start();

        System.out.println("zk client start successfully!!");


        //register watcher
        PathChildrenCache pathChildrenCache = new PathChildrenCache(curatorFrameworkClient, watcherNode, true);
        pathChildrenCache.getListenable().addListener((client, event) -> {
            ChildData data = event.getData();
            if(null == data){
                System.out.println("no data in event [" + event +"]");
            }else {
                System.out.println(
                        "Receive event :" +
                                "type=["+ event.getType() +"], " +
                                "path=[" + data.getPath() + "]," +
                                "data=["+ data.getData() +"]," +
                                "state=[" + data.getStat() + "]"
                );
            }
        });
        pathChildrenCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
        System.out.println(" Register zookeeper watcher successfully!! Please operate in terminal to show the listener function");
        Thread.sleep(Integer.MAX_VALUE);

    }
}
